﻿using System;
using System.Web.Mvc;
using Shell.DomainDot;
using Framework.Poco;
using Framework.Domain;

namespace Framework.Mvc.Controllers
{
    public class AgencyLogoController : Controller
    {
        private IDomainDotFactory factory;

        public AgencyLogoController()
        {
            factory = DomainDotFactory.Factory;
        }

        /// <summary>
        /// 创建经销商的Logo
        /// </summary>
        [HttpGet]
        public ActionResult Create(Agency currentAgency)
        {
            if (currentAgency != null)
            {
                var context = factory.Create<AgencyBinaryFileContext>(currentAgency.Id);
                var logo = context.GetBinaryFile();
                var model = new AgencyLogoCreateViewModel(logo);
                return View(model);
            }
            return this.RedirectToAction("LogOn", "Agency");
        }

        /// <summary>
        /// 创建经销商的Logo
        /// </summary>
        [HttpPost]
        public ActionResult Create(Agency currentAgency, FilesUploaded filesUploaded)
        {
            if (currentAgency != null)
            {
                if (filesUploaded != null && filesUploaded.Identities.Count == 1)
                {
                    var context = factory.Create<AgencyBinaryFileContext>(currentAgency.Id);
                    context.BindBinaryFile(filesUploaded.Identities[0]);
                    var logo = context.GetBinaryFile();
                    var model = new AgencyLogoCreateViewModel(logo);
                    return View(model);
                }
                this.ModelState.AddModelError("filesUploaded", "图片不符合要求!");
                return View();
            }
            return this.RedirectToAction("LonOn", "Agency");
        }

        /// <summary>
        /// 删除经销商LOGO
        /// </summary>
        public ActionResult Delete(Agency currentAgency, Guid identity)
        {
            if (currentAgency != null)
            {
                var context = factory.Create<AgencyBinaryFileContext>(currentAgency.Id);
                context.Delete(identity);
                return this.RedirectToAction("Create");
            }
            return this.RedirectToAction("LogOn", "Agency");
        }
    }
}